export default {
  name: '',
  data () {
    return {
      // 关联用户在表单内填写的数据
      info: {},
      // 关联这个表单的验证规则
      loginRules: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'change' },
          { min: 3, message: '最少输入3位字符' }
        ],
        password: [
          { required: true, message: '请填写密码', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 表单重置事件
    resetHandler () {
      this.$refs.login.resetFields()
    },
    submitHandler () {
      this.$refs.login.validate(async valid => {
        if (!valid) {
          this.$message({
            type: 'warning',
            message: '请按规则填写表单'
          })
          return
        }

        // console.log('我要提交表单了')
        const { data, meta } = await this.$post('login', this.info)

        if (meta.status === 400) {
          this.$message({
            type: 'error',
            message: '用户名或密码错误',
            duration: 3000
          })
          return
        }
        // 把token存储到sessionstorage内
        window.sessionStorage.setItem('token', data.token)

        this.$message({
          type: 'success',
          message: '登录成功，即将跳转',
          duration: 1500
        })

        setTimeout(() => {
          // 跳转到/home
          this.$router.push('/home')
        }, 1500)
      })
    }
  }
}
